package com.study.javaOther.reference;


import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * @Name: MainTest
 * @Description: java类作用描述
 * @Author: yn
 * @CreateDate: 2022/6/15 10:13
 * @Remark: 特殊说明
 * @Version: 1.0
 */
public class MainTest {

    static Cache<Long, Info> cache = Caffeine.newBuilder()
            .expireAfterAccess(1, TimeUnit.HOURS)
            .weakValues()
            .initialCapacity(1)
            .maximumSize(10)
            .build();
    public static void main(String[] args) {
        JSONObject jsonObject=new JSONObject();
        System.out.println("创建前缓存：  "+cache.asMap());
        for (long i = 158; i < 168; i++) {
            jsonObject.put("i="+i,cache.get(i,k->createInfo(k+"")));
        }
        System.out.println("GC前cache.getIfPresent(158) = " + cache.getIfPresent(158L));
        jsonObject.clear();
        System.out.println("---------------GC---------------");
        System.gc();
        System.out.println("GC后cache.getIfPresent(158) = " + cache.getIfPresent(158L));
        System.out.println("cache.estimatedSize() = " + cache.estimatedSize());
        System.out.println("cache.asMap() = " + cache.asMap());
    }

    private static Info createInfo(Long k) {
        System.out.println("创建");
        Info info = new Info();
        info.setId(k);
        info.setName(k);
        return info;
    }

    private static Info createInfo(String k) {
        Info info = new Info();
        info.setId(Long.parseLong(k));
        info.setName(Long.parseLong(k));
        return info;
    }
}

class Info {
    private Long id;
    private Long name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getName() {
        return name;
    }

    public void setName(Long name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Info{" +
                "id=" + id +
                ", name=" + name +
                '}';
    }
}
